package com.example.cinemaorder.util;

import com.alibaba.fastjson2.JSON;
import com.example.cinemaorder.entity.SysMovie;
import lombok.Data;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.sql.*;

//同步电影id、票房——支付时增加票房
@Component
public class MysqlToRedis {

    // Redis连接设置
    String redisHost = "localhost";
    int redisPort = 6379;

    // MySQL连接设置
    String mysqlHost = "192.168.159.166";
    int mysqlPort = 33306;
    String mysqlDatabase = "cenima_system";
    String mysqlUsername = "root";
    String mysqlPassword = "123";

    // 使用@PostConstruct注解，让这个方法在类加载时执行一次
    @PostConstruct
    public void importData() {
        try {
            // 建立MySQL连接
            String mysqlUrl = String.format("jdbc:mysql://%s:%d/%s", mysqlHost, mysqlPort, mysqlDatabase);
            Connection mysqlConn = DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword);

            // 建立Redis连接
            Jedis jedis = new Jedis(redisHost, redisPort);

            // 查询MySQL数据
            String sql = "SELECT movie_id,movie_box_office FROM sys_movie";
            Statement statement = mysqlConn.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            // 将MySQL数据导入Redis
            while (resultSet.next()) {
                String key = resultSet.getString("movie_id");
                String value = resultSet.getString("movie_box_office");

                // 使用SET命令将数据存储到Redis的hash中
                jedis.set("电影票房："+key, value);
            }

            // 关闭连接
            resultSet.close();
            statement.close();
            mysqlConn.close();
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
